﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Yaml;
using System.IO;

namespace EcologyFuture.DataStorage
{
  using EcologyFuture.DataCollection;
  /// <summary>
  /// The <c>DataStorageKernel</c> class is the main class in <c>DataStorage</c> module. It 
  /// manages all operations with data storage.
  /// </summary>
  class DataStorageKernel
  {
    /// <summary>
    /// Initializes a new instance of <c>DataStorageKernel</c> class.
    /// </summary>
    public DataStorageKernel()
    {

    }
    /// <summary>
    /// Saves all collect weather data to storage (yaml files).
    /// </summary>
    /// <param name="data">List of <c>WeatherInfo</c> from all data sources.</param>
    public void Save(List<WeatherInfo> data)
    {
      foreach (WeatherInfo wi in data)
      {
        string te = wi.date.ToString();
        Mapping mapping = new Mapping(
          new MappingNode[]
          {
            new MappingNode(new Yaml.String("date"), new Yaml.String(wi.date.ToString())),
            new MappingNode(new Yaml.String("country"), new Yaml.String(wi.country)),
            new MappingNode(new Yaml.String("city"), new Yaml.String(wi.city)),
            new MappingNode(
              new Yaml.String("wind"),
              new Mapping(
                new MappingNode[] {
                  new MappingNode(new Yaml.String("direction"), new Yaml.String(wi.direction.ToString())),
                  new MappingNode(new Yaml.String("speed"), new Yaml.String(wi.speed.ToString()))
                }
              )
            ),
            new MappingNode(new Yaml.String("humidity"), new Yaml.String(wi.humidity.ToString())),
            new MappingNode(new Yaml.String("pressure"), new Yaml.String(wi.pressure.ToString())),
            new MappingNode(new Yaml.String("temperature"), new Yaml.String(wi.temperature.ToString()))
          }
        );
        string fileName = wi.dataCollectorName + "_" + wi.date.ToShortDateString() + "_" + wi.date.ToShortTimeString().Replace(':', '-');
        StreamWriter streamWriter = new StreamWriter(fileName + ".yaml");
        streamWriter.Write(mapping.Write());
        streamWriter.Close();
      }
    }
  }
}
